package main

import (
	"encoding/json"
	"fmt"
	"github.com/micro/go-micro/v2"
	"github.com/micro/go-micro/v2/broker"
	"github.com/micro/go-plugins/broker/http/v2"
	_ "github.com/micro/go-plugins/broker/http/v2"
	"github.com/micro/go-plugins/registry/etcdv3/v2"
	"gomicro/brokerMicro/proto"
	"log"
)

var pubSub broker.Broker

func main() {

	//实例化
	etcdr := etcdv3.NewRegistry()
	
	service := micro.NewService(
		micro.Name("go.micro"),
		micro.Version("v2.7.0"),
		micro.Broker(http.NewBroker()),
		micro.Registry(etcdr),
	)

	//初始化
	service.Init()

	//订阅事件
	pubSub = service.Server().Options().Broker
	if err := pubSub.Connect(); err != nil {
		log.Fatal(" broker connect failed , error is : %v\n", err)
	}

	fmt.Println("执行")

	_, sErr := pubSub.Subscribe("go.micro.first.message", func(event broker.Event) error {
		var req *message.StudentRequest


		fmt.Println("消息体:", string(event.Message().Body))

		if jErr := json.Unmarshal(event.Message().Body, &req); jErr != nil {
			return jErr
		}
		fmt.Println(" 接收到信息：", req)
		//去执行其他操作
		return nil
	})

	if sErr != nil {
		log.Printf("sub error: %v\n", sErr)
	}

	if rErr := service.Run(); rErr != nil {
		log.Fatal(sErr.Error())
	}
}
